/*
 * @author hope.chen, QQ:77132995, email:kazeik@163.com
 * 2020-12-24 12:36
 * 类说明:
 */

import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_scan_crop/utils/ApiUtils.dart';
import 'package:image_scan_crop/utils/Utils.dart';

class RequestInterceptor extends InterceptorsWrapper {
  bool? hide;

  RequestInterceptor({this.hide});

  @override
  Future onRequest(RequestOptions options, handler) async {
    if (null != hide && !hide!) EasyLoading.show(status: "加载中..");
    String request = '''
      ============= 请求开始 =============  
      baseUrl = ${options.baseUrl}
      method = ${options.method.toString()}
      url = ${options.uri.toString()}
      path = ${options.path}
      headers = ${options.headers}
      params = ${options.queryParameters}
      extra = ${options.extra.toString()}
      ''';
    Utils.logs(request);
    if (options.method.toString().toUpperCase() == "POST") {
      if (options.data != null) {
        if (options.data is FormData) {
          Utils.logs(
              "formData = ${(options.data as FormData).fields.map((e) => e.key + " = " + e.value)}");
        } else {
          Utils.logs("body = ${jsonEncode(options.data)}");
        }
      }
    }
    // return options;
    return handler.next(options);
  }

  @override
  Future onError(DioError e, handler) async {
    EasyLoading.dismiss();
    // String error = '''
    //   =============  错误响应数据=============
    //   type = ${e.type}
    //   message = ${e.message}
    //   stackTrace = ${e.error.toString()}
    //   ''';
    // Utils.logs(error);
    return handler.next(e);
  }

  @override
  Future onResponse(Response options, handler) async {
    EasyLoading.dismiss();
    String response = '''
        ============= 响应数据=============
        url = ${options.requestOptions.uri}
        path = ${options.requestOptions.path}
        code = ${options.statusCode}
        data = ${options.data}
        ''';
    Utils.logs(response);
    return handler.next(options);
  }
}
